<!-- 文章评论 -->
<template>
  <!-- :immediate-check="false"  是否在初始化时立即执行滚动位置检查 -->
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
    :error.sync="error"
    :immediate-check="false"
    error-text="加载失败，请点击重试"
  >
    <CommentItem
      @reply-click="$emit('reply-click', $event)"
      v-for="(item, index) in list"
      :key="index"
      :comment="item"
    />
  </van-list>
</template>

<script>
import { getComment } from "@/api/comment";
import CommentItem from "./comment-item.vue";

export default {
  name: "CommenteList",
  components: {
    CommentItem,
  },
  props: {
    source: {
      type: [Number, String, Object],
      required: true,
    },
    list: {
      type: Array,
      // 默认给一个空数组
      default: () => [],
    },
    type: {
      type: String,
      validator(value) {
        return ["a", "c"].includes(value);
      },
      default: "a",
    },
  },
  data() {
    return {
      // list: [],
      loading: false,
      finished: false,
      offset: null,
      limit: 10,
      error: false,
    };
  },
  created() {
    this.loading = true;
    this.onLoad();
  },
  methods: {
    async onLoad() {
      try {
        const { data } = await getComment({
          type: this.type,
          source: this.source.toString(), // toString() 防止大数字 原文id
          offset: this.offset,
          limit: this.limit,
        });
        const { results } = data.data;
        this.list.push(...results);
        // 将文章的数据传递到外部
        this.$emit("onload-success", data.data);
        this.loading = false;
        if (results.length) {
          this.offset = data.data.last_id;
        } else {
          this.finished = true;
        }
      } catch (err) {
        // console.log("获取失败", err);
        this.error = true;
        this.loading = false;
      }
    },
  },
};
</script>

<style></style>
